package com.bingbaihanji.core.config.security;

import com.bingbaihanji.core.config.security.jwt.JwtProperties;
import com.bingbaihanji.core.config.security.jwt.JwtTokenUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static com.bingbaihanji.core.config.security.SpringSecurityConfig.APPLICATION_JSON_UTF8_VALUE;


/**
 * 自定义认证成功处理器
 */
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private static final Logger log = LoggerFactory.getLogger(MyAuthenticationSuccessHandler.class);

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication)
            throws IOException, ServletException {

       log.debug(jwtProperties.getBase64Secret());
       log.debug(jwtProperties.getHeader());
       log.debug(jwtProperties.getTokenValidityInSeconds().toString());
        //生成token
        final String realToken = jwtTokenUtil.generateToken(authentication.getName());
        // 获取用户身份信息
        Object principal = authentication.getPrincipal();
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("token", realToken);
        map.put("message", "登录成功");
        map.put("data", principal);

        //将生成的authentication放入容器中，生成安全的上下文
        SecurityContextHolder.getContext().setAuthentication(authentication);

        response.setStatus(HttpStatus.OK.value());
        response.setContentType(APPLICATION_JSON_UTF8_VALUE);

        String json = new ObjectMapper().writeValueAsString(map);

        response.getWriter().println(json);

    }
}
